# Copyright (c) 2024 Cypress Semiconductor Corporation.
# SPDX-License-Identifier: Apache-2.0

zephyr_sources(soc.c)
zephyr_sources(mpu_regions.c)
zephyr_include_directories(.)

zephyr_sources_ifdef(CONFIG_PM power.c)

# CAT1B family defines
zephyr_compile_definitions_ifdef(CONFIG_SOC_FAMILY_INFINEON_CAT1 CY_USING_HAL)
zephyr_compile_definitions_ifdef(CONFIG_SOC_FAMILY_INFINEON_CAT1B COMPONENT_CAT1B)
zephyr_compile_definitions(COMPONENT_CM33)

# In MTB for APPTYPE == flash: -DFLASH_BOOT -DCY_PDL_FLASH_BOOT
zephyr_compile_definitions(FLASH_BOOT)
zephyr_compile_definitions(CY_PDL_FLASH_BOOT)

# Use custom linker script
set(SOC_LINKER_SCRIPT ${ZEPHYR_BASE}/soc/infineon/cat1b/cyw20829/linker.ld CACHE INTERNAL "")

# Get sram_bootstrap address and size
dt_nodelabel(sram_bootstrap NODELABEL "sram_bootstrap")
dt_reg_addr(bootstrap_dst_addr PATH ${sram_bootstrap})
dt_reg_size(bootstrap_size PATH ${sram_bootstrap})

set(gen_app_header_args)
set(app_signed_enc_path ${ZEPHYR_BINARY_DIR}/${KERNEL_NAME})

if(CONFIG_INFINEON_SECURE_LCS OR (DEFINED CONFIG_MCUBOOT_ENCRYPTION_KEY_FILE) OR (DEFINED CONFIG_MCUBOOT_SIGNATURE_KEY_FILE))
  # Check cysecuretools
  find_program(CYSECURETOOLS cysecuretools REQUIRED)
  message("-- Found cysecuretools: ${CYSECURETOOLS}")

  # Locate CySecureTools policy file
  if(IS_ABSOLUTE "${CONFIG_INFINEON_SECURE_POLICY}")
    cmake_path(SET cysecuretools_policy "${CONFIG_INFINEON_SECURE_POLICY}")
  else()
    find_file(
      cysecuretools_policy
      NAMES
        "${CONFIG_INFINEON_SECURE_POLICY}"
      PATHS
        "${APPLICATION_SOURCE_DIR}"
        "${WEST_TOPDIR}"
        "${SOC_FULL_DIR}/cyw20829"
      NO_DEFAULT_PATH
      )
  endif()

  if(NOT IS_ABSOLUTE "${cysecuretools_policy}" OR NOT EXISTS "${cysecuretools_policy}")
    message(FATAL_ERROR "Can't find policy file \"${CONFIG_INFINEON_SECURE_POLICY}\" "
                        "(Note: Relative paths are searched through "
                        "APPLICATION_SOURCE_DIR=\"${APPLICATION_SOURCE_DIR}\" "
                        "and WEST_TOPDIR=\"${WEST_TOPDIR}\")")
  endif()

  message("-- Using cysecuretools policy: ${cysecuretools_policy}")
  set(CYSECURETOOLS_POLICY ${cysecuretools_policy} CACHE PATH "cysecuretools policy")
endif()

if(CONFIG_INFINEON_SECURE_LCS)
  #
  # Additional postbuild action for SECURE LCS
  #
  set(gen_app_header_args ${gen_app_header_args} --secure_lcs True)
  set(app_signed_path ${ZEPHYR_BINARY_DIR}/${KERNEL_NAME}.signed)
  set(app_signed_enc_path "${app_signed_path}")

  if(CONFIG_INFINEON_SMIF_ENCRYPTION)
    set(gen_app_header_args ${gen_app_header_args} --smif-config ${ZEPHYR_BINARY_DIR}/nonce-output.bin)
    set(enc_option --encrypt --nonce-output nonce-output.bin)
    # The encrypted image file path generated by cysecuretools
    set(app_signed_enc_path "${app_signed_path}_encrypted")
  endif()

  set(bin2hex_option bin2hex --image ${app_signed_enc_path}.bin --output ${app_signed_enc_path}.hex --offset 0x60000030)

  # Sign Zephyr L1 app in SECURE LCS
  set_property(GLOBAL APPEND PROPERTY extra_post_build_commands
    COMMAND ${CYSECURETOOLS} -q -t cyw20829
      -p ${cysecuretools_policy} sign-image --image-format bootrom_next_app
      -i ${ZEPHYR_BINARY_DIR}/${KERNEL_BIN_NAME} -k 0 -o ${app_signed_path}.bin
      --slot-size ${CONFIG_FLASH_LOAD_SIZE} --app-addr 0x08000030
      ${enc_option} ${bin2hex_option}
    )
endif()

# By default the MCUboot header size if set to 0x400 by the cysecuretools
# https://github.com/Infineon/edgeprotecttools/blob/master/docs/README_GENERAL.md#sign-image
set(mcuboot_header_offset 0)
if((DEFINED CONFIG_MCUBOOT_ENCRYPTION_KEY_FILE) OR (DEFINED CONFIG_MCUBOOT_SIGNATURE_KEY_FILE))
set(mcuboot_header_offset 0x400)
endif()

# Calculate the place in flash
math(EXPR flash_addr_offset
  "${CONFIG_CYW20829_FLASH_SAHB_ADDR} + ${CONFIG_FLASH_LOAD_OFFSET} + ${mcuboot_header_offset}"
  OUTPUT_FORMAT HEXADECIMAL
)
set(gen_app_header_args ${gen_app_header_args} --flash_addr_offset ${flash_addr_offset} )

# Generate platform specific header (TOC2, l1_desc, etc)
set_property(GLOBAL APPEND PROPERTY extra_post_build_commands COMMAND
    ${PYTHON_EXECUTABLE} ${ZEPHYR_BASE}/soc/infineon/cat1b/cyw20829/gen_app_header.py
    -p ${ZEPHYR_BINARY_DIR} -n ${KERNEL_NAME} ${gen_app_header_args}
    --bootstrap-size ${bootstrap_size}
    --bootstrap-dst-addr ${bootstrap_dst_addr}
  )

set(MERGED_FILE ${CMAKE_BINARY_DIR}/zephyr/zephyr_merged.hex  CACHE PATH "merged hex")

# Merge platform specific header and zephyr image to a single binary.
set_property(GLOBAL APPEND PROPERTY extra_post_build_commands
  COMMAND ${PYTHON_EXECUTABLE} ${ZEPHYR_BASE}/scripts/build/mergehex.py
    -o ${MERGED_FILE}
    ${app_signed_enc_path}.hex ${ZEPHYR_BINARY_DIR}/app_header.hex
  )

set_property(GLOBAL APPEND PROPERTY extra_post_build_byproducts ${MERGED_FILE})

# Use custom mcuboot cmake for sign/encrypt by using cysecuretools
if(CONFIG_BOOTLOADER_MCUBOOT)
  set_target_properties(zephyr_property_target PROPERTIES SIGNING_SCRIPT
    ${CMAKE_CURRENT_LIST_DIR}/mcuboot.cmake)
endif()
